/*
 * @Author: xiawei 1243162387@qq.com
 * @Date: 2024-03-28 13:54:55
 * @LastEditors: xiawei 1243162387@qq.com
 * @LastEditTime: 2024-04-18 11:31:18
 */
import axios, { type AxiosResponse, type AxiosInstance } from 'axios';
// 创建axios实例
const service = axios.create({
  baseURL: '', // api的base_url
  timeout: 5000 // 请求超时时间
});
 
export type ResponseType = {
  code: number,
  result: any,
}
// 请求拦截器
service.interceptors.request.use(
  config => {
    // 可以在这里添加请求头等信息
    const userStr = localStorage.getItem('userInfo')
    if (userStr) {
      config.headers['X-Token'] = JSON.parse(userStr)?.token;
    }
    return config;
  },
  error => {
    // 请求错误处理
    Promise.reject(error);
  }
);
 
// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data;
    if (res.code !== 20000) {
      // 50001: 非法的token; 50002: 其他客户端错误; 50003: 认证失败; 50004: 授权失败; 50005: 未找到用户
      if (res.code === 50001 || res.code === 50002 || res.code === 50003 || res.code === 50004 || res.code === 50005) {
        // 跳转到登录页面
        location.reload();
      }
          // 在内部消化掉这个业务异常
      return Promise.reject(res.errors)
    }else{
      return res;
    }
  },
  error => {
    return Promise.reject(error);
  }
);

export type Request =  AxiosInstance;
export const request: Request = service;